import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || '/dev-api', // url = base url + request url; default to proxy prefix
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // 保持请求头类型由调用方决定，若未设置在 POST JSON 场景下设置默认值
    const existingContentType = config.headers['Content-Type'] || config.headers['content-type']
    if (!existingContentType && config.method === 'post') {
      // 默认按 JSON 发送，axios 会自动序列化
      config.headers['Content-Type'] = 'application/json; charset=UTF-8'
    }
    if (!config.headers['Accept'] && !config.headers['accept']) {
      config.headers['Accept'] = 'application/json'
    }

    // 添加 token 到请求头
    const token = getToken()
    if (token) {
      // 使用标准的 Authorization 头
      config.headers['Authorization'] = `Bearer ${token}`
      // 保留原有的 X-Token 以兼容后端
      config.headers['X-Token'] = token
    }

    // 显式序列化 JSON，避免个别环境下 body 丢失
    const contentType = (config.headers['Content-Type'] || config.headers['content-type'] || '').toLowerCase()
    const method = (config.method || 'get').toLowerCase()
    const isJson = contentType.startsWith('application/json')
    const isBodyMethod = method === 'post' || method === 'put' || method === 'patch'
    const isPlainObject = Object.prototype.toString.call(config.data) === '[object Object]'
    const isFormData = typeof FormData !== 'undefined' && config.data instanceof FormData
    const isBlob = typeof Blob !== 'undefined' && config.data instanceof Blob

    if (isBodyMethod && isJson && isPlainObject && !isFormData && !isBlob) {
      config.data = JSON.stringify(config.data)
    }

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    
    // 处理 token 相关错误
    if (error.response) {
      const { status, data } = error.response
      
      // 401 Unauthorized - token 无效或过期
      if (status === 401) {
        Message({
          message: 'Token expired or invalid, please login again',
          type: 'error',
          duration: 5 * 1000
        })
        
        // 清除 token 并跳转到登录页
        removeToken()
        store.commit('user/SET_TOKEN', '')
        
        // 如果不在登录页，则跳转
        if (router.currentRoute.path !== '/login') {
          router.push('/login')
        }
        return Promise.reject(error)
      }
      
      // 403 Forbidden - 权限不足
      if (status === 403) {
        Message({
          message: 'Access denied, insufficient permissions',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(error)
      }
      
      // 其他 HTTP 错误
      Message({
        message: data?.message || `Request failed with status ${status}`,
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.request) {
      // 网络错误
      Message({
        message: 'Network error, please check your connection',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      // 其他错误
      Message({
        message: error.message || 'Request error',
        type: 'error',
        duration: 5 * 1000
      })
    }
    
    return Promise.reject(error)
  }
)

export default service